import java.util.Arrays;

public class Leet_529 {
    public static void main(String[] args) {
        char[][] a = {{'E', 'E', 'E', 'E', 'E'},
        {'E', 'E', 'M', 'E', 'E'},
        {'E', 'E', 'E', 'E', 'E'},
        {'E', 'E', 'E', 'E', 'E'}};
        Leet_529 l = new Leet_529();

        System.out.println(Arrays.deepToString(l.updateBoard(a, new int[]{3, 0})));
    }
    public char[][] updateBoard(char[][] board, int[] click) {
        if (board[click[0]][click[1]]=='M'){
            board[click[0]][click[1]]='X';
            return board;
        }else{
            dfs(board,click);
        }
        return board;
    }
    void dfs(char[][] board, int[] click){
        if (click[0]<0||click[0]>board.length-1||click[1]<0||click[1]>board[0].length-1)
            return;
        if (check(board,click)=='B'&&board[click[0]][click[1]]=='E'){
            board[click[0]][click[1]]='B';
            dfs(board, new int[]{click[0]+1, click[1]});
            dfs(board, new int[]{click[0]+1, click[1]+1});
            dfs(board, new int[]{click[0]+1, click[1]-1});
            dfs(board, new int[]{click[0]-1, click[1]+1});
            dfs(board, new int[]{click[0]-1, click[1]});
            dfs(board, new int[]{click[0]-1, click[1]-1});
            dfs(board, new int[]{click[0], click[1]-1});
        }else {
            board[click[0]][click[1]]=check(board,click);
        }

    }
    char check(char[][] board, int[] click){
        int num = 0;
        try{
            if (board[click[0]+1][click[1]]=='M')
                num++;
        }catch (Exception ignored){}
        try{
            if (board[click[0]+1][click[1]+1]=='M')
                num++;
        }catch (Exception ignored){}
        try{
            if (board[click[0]+1][click[1]-1]=='M')
                num++;
        }catch (Exception ignored){}
        try{
            if (board[click[0]][click[1]+1]=='M')
                num++;
        }catch (Exception ignored){}
        try{
            if (board[click[0]][click[1]-1]=='M')
                num++;
        }catch (Exception ignored){}
        try{
            if (board[click[0]-1][click[1]]=='M')
                num++;
        }catch (Exception ignored){}
        try{
            if (board[click[0]-1][click[1]+1]=='M')
                num++;
        }catch (Exception ignored){}
        try{
            if (board[click[0]-1][click[1]-1]=='M')
                num++;
        }catch (Exception ignored){}
        if (num==0)
            return 'B';
        return (char)('0'+num);
    }

}
